package com.demo2do.boyle.backend.web.controller.report;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo2do.boyle.backend.cache.accessor.PersistentAccessor;
import com.demo2do.boyle.backend.service.aduser.AduserService;
import com.demo2do.boyle.backend.service.report.AdvertisementDtoService;
import com.demo2do.boyle.backend.service.report.AdvertisementStatisticsService;
import com.demo2do.boyle.backend.service.report.StatisticsConvergeService;
import com.demo2do.boyle.backend.service.report.impl.utils.DateUtils;
import com.demo2do.boyle.common.entity.aduser.Aduser;
import com.demo2do.boyle.common.entity.advertisement.AdvertisementDto;
import com.demo2do.boyle.common.entity.report.StatisticsConverge;
import com.demo2do.boyle.common.entity.system.tag.Tag;
import com.demo2do.core.persistence.support.Filter;
import com.demo2do.core.utils.StringUtils;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Page;

/**
 * 
 * @author downpour Jason.Y
 */
@Controller
@RequestMapping("/reports")
@MenuSetting("menu-report")
public class ReportAduserController {

	@Autowired
	private AduserService aduserService;
	
	@Autowired
	private StatisticsConvergeService statisticsConvergeService;
	
	@Autowired
	private AdvertisementDtoService advertisementDtoService;
	
	@Autowired
	private AdvertisementStatisticsService advertisementStatisticsService;
	
	@Autowired
	private PersistentAccessor persistentAccessor;

	/**
     * do search
     * 
     * @return
     */
    @RequestMapping(value = "/aduser")
    @MenuSetting("submenu-report-aduser")
    public ModelAndView onSearch(Page page, HttpServletRequest request,
            @RequestParam(value = "period", required = false) String period) {

        ModelAndView modelAndView = new ModelAndView("report/report-aduser-list");

        Filter filter = null;
        
        if (StringUtils.isEmpty(period) || "MONTH".equals(period)) {
        	filter = new Filter().addDateTimeBetween("createTime", DateUtils.getCurrentMonthStartTime(), DateUtils.getCurrentMonthEndTime());
		}else if(!StringUtils.isEmpty(period) && "QUARTER".equals(period)){
			filter = new Filter().addDateTimeBetween("createTime", DateUtils.getCurrentQuarterStartTime(), DateUtils.getCurrentQuarterEndTime());
		}else{
			filter = new Filter().addDateTimeBetween("createTime", DateUtils.getCurrentYearStartTime(), DateUtils.getCurrentYearEndTime());
		}
		
        int count = aduserService.count(Aduser.class, filter);
        modelAndView.addObject("count", count);
        modelAndView.addObject("period", period);
        
        if(count > 0) {
        	List<Aduser> adusers = aduserService.list(Aduser.class, filter, page);
            modelAndView.addObject("adusers", adusers);
        }
        
        if (period != null) {
			Map<String, String> queries = StringUtils.parseQueryString("period=" + period);
			if (queries.containsKey("page")) {
				queries.remove("page");
			}
			modelAndView.addObject("queryString", StringUtils.toQueryString(queries));
		}else{
			modelAndView.addObject("queryString", null);
		}
        
        return modelAndView;
    }
    
	/**
	 * view report converges view
	 * 
	 * @return
	 */
	@RequestMapping("/aduser/statisticsconverges/{aduserId}/detail")
	@MenuSetting("submenu-report-aduser")
	public ModelAndView viewDetail(@PathVariable("aduserId") Integer id, Page page) {

		ModelAndView modelAndView = new ModelAndView("report/report-aduser-view");

		List<StatisticsConverge> statisticsConverges = statisticsConvergeService.list(StatisticsConverge.class, page);
		
		for (StatisticsConverge statisticsConverge : statisticsConverges) {
			AdvertisementDto advertisementDto = advertisementDtoService.loadById(AdvertisementDto.class, statisticsConverge.getAdvertisementId());
			statisticsConverge.setAdvertisementDto(advertisementDto);
		}
		
		modelAndView.addObject("statisticsconverges", statisticsConverges);

		return modelAndView;
	}

	/**
	 * view report advertisement view
	 * 
	 * @return
	 */
	@RequestMapping("/aduser/statisticsconverges/{advertisementId}/chart")
	@MenuSetting("submenu-report-aduser")
	public ModelAndView viewAdvertisementChart(@PathVariable("advertisementId") Integer id, Page page) {

		ModelAndView modelAndView = new ModelAndView("report/report-aduser-adverchart");

		Map<String, Object> advertisementStatisticsDto = advertisementStatisticsService.queryForObject(id);
		
		List<Map<String, Object>> ageTagList = advertisementStatisticsService.listByAge(id);
		
		modelAndView.addObject("advertisementStatisticsDto", advertisementStatisticsDto);
	
		/* age distribution  */
		JSONArray  jsonArrPeriod = new JSONArray();
		JSONObject jsonObjPeriod = null;
		
		JSONArray  jsonArr1 = new JSONArray();
		JSONObject jsonObj2 = null;
		JSONArray  jsonArrM = null;
		JSONArray  jsonArrW = null;
		JSONArray  jsonArrA = null;
		
		
		for (String key1 : persistentAccessor.getAgeTags().keySet()) {
			jsonObjPeriod = new JSONObject();
			
			jsonObj2 = new JSONObject();
			jsonArrM = new JSONArray();
			jsonArrW = new JSONArray();
			jsonArrA = new JSONArray();
			
			for (Map<String, Object> map : ageTagList) {
				int sum = 0;
				
				for (String key2 : map.keySet()) {
					if ("tag".equals(key2)) {
						if(persistentAccessor.getAgeTags().keySet().contains(map.get(key2).toString()))
						{
							Tag tag = (Tag)persistentAccessor.getAgeTags().get(key1);
							
							jsonObjPeriod.put("text", tag.getName());
							jsonObjPeriod.put("max", 100);
						}
					}else if("man".equals(key2)){
						
							BigDecimal intVal = (BigDecimal)map.get(key2);
							
							sum += intVal.intValue();
							
							jsonArrM.add(map.get(key2));
							
					}else if("woman".equals(key2)){
							
							BigDecimal intVal = (BigDecimal)map.get(key2);
						
							sum += intVal.intValue();
							
							jsonArrW.add(map.get(key2));
					}
					
				}
				
				jsonArrA.add(sum);
				
			}
			
			
			jsonArrPeriod.add(jsonObjPeriod);
		}
		
		jsonObj2.put("name", "男");
		
		for (int i = 0; i < persistentAccessor.getAgeTags().keySet().size() - ageTagList.size(); i++) {
			jsonArrM.add(0);
		}
		
		jsonObj2.put("value", jsonArrM);
		jsonArr1.add(jsonObj2);
		
		jsonObj2 = new JSONObject();
		jsonObj2.put("name", "女");
		
		for (int i = 0; i < persistentAccessor.getAgeTags().keySet().size() - ageTagList.size(); i++) {
			jsonArrW.add(0);
		}
		
		jsonObj2.put("value", jsonArrW);
		jsonArr1.add(jsonObj2);
		
		jsonObj2 = new JSONObject();
		jsonObj2.put("name", "总共");
		
		for (int i = 0; i < persistentAccessor.getAgeTags().keySet().size() - ageTagList.size(); i++) {
			jsonArrA.add(0);
		}
		
		jsonObj2.put("value", jsonArrA);
		jsonArr1.add(jsonObj2);
		
		
		modelAndView.addObject("indicator", jsonArrPeriod.toString());
		modelAndView.addObject("radar", jsonArr1.toString());
		
		return modelAndView;
	}

	/**
	 * view report advertisement chart view
	 * 
	 * @return
	 */
	@RequestMapping("/aduser/{aduserId}/chart")
	@MenuSetting("submenu-report-aduser")
	public ModelAndView viewChart(@PathVariable("aduserId") Integer id, Page page) {

		ModelAndView modelAndView = new ModelAndView("report/report-aduser-chart");

		return modelAndView;
	}
}
